package com.icecloud.cloud.upms.conf.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.icecloud.cloud.upms.entity.base.BaseCoreUser;
import com.icecloud.cloud.upms.service.CoreUserService;

@Service
public class IceCloudDetailsService implements UserDetailsService {

	protected static Logger logger = Logger.getLogger("Jr5108UserDetailsService");

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		BaseCoreUser account = service.findbyName(username);
		if(account != null){
		UserDetails userDetails = new User(username, account.getPassword(), true, true, true, true,
				getAuthorities(null));
		// 这里用户权限没有设置
		return userDetails;
		}
		throw new AuthenticationServiceException(username+"：用户名不正确！");
	}

	/**
	 * 获得访问角色权限
	 * 这里先不用角色权限，
	 * 
	 * @param access
	 * @return
	 */
	public Collection<GrantedAuthority> getAuthorities(String role) {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(1);
		if(StringUtils.isNotBlank(role)){
		// 所有的用户默认拥有ROLE权限
		logger.debug("Grant ROLE to this user");
		authList.add(new SimpleGrantedAuthority("ROLE_" + role));
		}
		return authList;
	}

	@Autowired
	private CoreUserService service;

}
